package com.ray.services;

import com.jfinal.plugin.activerecord.Record;
import com.ray.controller.base.BaseController;
import com.ray.exception.TransactionalException;
import com.ray.interceptor.base.AopContext;
import com.ray.interceptor.base.MetaObjectIntercept;
import com.ray.model.DataObject;
import com.ray.util.Commen;
import com.ray.util.Ret;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TemplateService extends BaseController {


    /**
     * 新增和新增后的事务处理
     *
     * @param object
     * @param model
     * @param intercept
     * @param ac
     * @throws Exception
     */
    @Transactional
    public void addAndAddafter(DataObject object, Record model, MetaObjectIntercept intercept, AopContext ac) throws Exception {
        dbService.save(object.getDataSource(), object.getTableName(), model);
        Ret res = intercept.addAfter(ac);
        if (!Commen.isEmptyy(res))
            throw new TransactionalException(res.get("msg").toString());
    }

    /**
     * 修改和修改后的事务处理
     *
     * @param object
     * @param model
     * @param intercept
     * @param ac
     * @throws Exception
     */
    @Transactional
    public void updateAndUpdateafter(DataObject object, Record model, MetaObjectIntercept intercept, AopContext ac) throws Exception {
        dbService.update(object.getDataSource(), object.getTableName(), model);
        Ret res = intercept.updateAfter(ac);
        if (!Commen.isEmptyy(res))
            throw new TransactionalException(res.get("msg").toString());
    }

    /**
     * 删除和删除后的事务处理
     *
     * @param object
     * @param model
     * @param intercept
     * @param ac
     * @throws Exception
     */
    @Transactional
    public void deleteAndDeleteafter(DataObject object, Record model, MetaObjectIntercept intercept, AopContext ac) throws Exception {
        dbService.delete(object.getDataSource(), object.getTableName(), model, getSessionUserId());
        Ret res = intercept.deleteAfter(ac);
        if (!Commen.isEmptyy(res))
            throw new TransactionalException(res.get("msg").toString());
    }

    /**
     * 导入和导入后的事务处理
     *
     * @param object
     * @param list
     * @param intercept
     * @param ac
     * @throws Exception
     */
    @Transactional
    public void importAndImportafter(DataObject object, List<Record> list, MetaObjectIntercept intercept, AopContext ac) throws Exception {
        dbService.batchSave(object.getDataSource(), object.getTableName(), list);
        Ret res = intercept.importAfter(ac);
        if (!Commen.isEmptyy(res))
            throw new TransactionalException(res.get("msg").toString());
    }
}
